import $func from '../utils/index.js'
import { ref } from 'vue'

// 创建通用数据管理函数的工厂函数
export function createCommonDataManager(apiConfig) {
  const { getRoles, getDepartments, getEmployees } = apiConfig
  
  const searchVal = ref('')
  const departments = ref({
    titleDepartments: [],
    childDepartments: [],
    employees: [],
  })
  const roles = ref({})
  
  const getRoleList = async () => {
    if (!getRoles) {
      console.warn('getRoles API function not provided')
      return
    }
    let { data: { list } } = await getRoles()
    roles.value = list;
  }
  
  const getDepartmentList = async (parentId = 0) => {
    if (!getDepartments) {
      console.warn('getDepartments API function not provided')
      return
    }

    let { data } = await getDepartments({ parentId })
    departments.value = data;
  }
  
  const getDebounceData = (event, type = 1) => {
    $func.debounce(async () => {
      if (event.target.value) {
        let data = {
          searchName: event.target.value,
          page: 1,
          size: 30
        }
        if (type == 1) {
          if (!getEmployees) {
            console.warn('getEmployees API function not provided')
            return
          }
          departments.value.childDepartments = [];
          let res = await getEmployees(data)
          departments.value.employees = res.data.list
        } else {
          if (!getRoles) {
            console.warn('getRoles API function not provided')
            return
          }
          let res = await getRoles(data)
          roles.value = res.data.list
        }
      } else {
        type == 1 ? await getDepartmentList() : await getRoleList();
      }
    })()
  }
  
  return {
    searchVal,
    departments,
    roles,
    getRoleList,
    getDepartmentList,
    getDebounceData
  }
}